<template>
  <div class="wrapper">
    <!--  -->
    <div class="title-but" v-show="titleBut">
      <el-button @click="oneClickSync">一键同步</el-button>
      <!-- <el-button>自动填充</el-button> -->
    </div>
    <LsdDialogTitle slot="dialog" :titleConfig="titleConfig" :activeNames="activeNames">
      <div slot="slot1">
        <div style="font-size: 18px;margin-bottom: 22px;">{{ formKey == "dutyDaily" ? '日报' : '日志' }}名称：&emsp;{{ reportName
        }}
        </div>
        <component :is="formKey" :type="isEdit" ref="dutyForm"></component>
        <AccessoryTable ref='AccessoryTable' :isEdit="isEdit" />
      </div>
      <div slot="slot2">
        <el-descriptions :labelStyle="{ display: 'inline-block', textAlign: 'right', width: '130px', fontSize: '18px' }"
          :contentStyle="{ fontSize: '18px' }">
          <el-descriptions-item label="填报人">{{ fillIn.creator }}</el-descriptions-item>
          <el-descriptions-item label="单位及部门">{{ fillIn.createDeptName }}</el-descriptions-item>
          <el-descriptions-item label="填报时间">{{ fillIn.reportTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="slot3">
        <el-form ref="approverForm" :model="approverForm" :rules="approverRules" label-width="140px" class="approverForm"
          :show-message="false">
          <el-form-item label="审批意见:">
            <el-input v-if="isApprover" v-model="approverForm.approvalOpinion"></el-input>
            <span v-else style="font-size: 18px;color: #606266;">{{ approverForm.approvalOpinion }}</span>
          </el-form-item>
        </el-form>
        <el-descriptions :labelStyle="{ display: 'inline-block', textAlign: 'right', width: '130px', fontSize: '18px' }"
          :contentStyle="{ fontSize: '18px' }">
          <el-descriptions-item label="审批人">{{ approve.approvalUser }}</el-descriptions-item>
          <el-descriptions-item label="单位及部门">{{ approve.approvalDept }}</el-descriptions-item>
          <el-descriptions-item label="审批时间">{{ approve.approvalTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </LsdDialogTitle>
    <div class="footer-btn">
      <!-- operator_leader  值班长 operator_staff 值班员 operator_director 值班主任 shift_leader 带班领导 -->
      <div v-if="submitBut && getParseStamp(calendarDate) == getParseStamp(new Date())">
        <el-button type="primary" @click="onSubmit({ reportApprovalStatus: 1 })">提交</el-button>
        <el-button @click="onSubmit({ reportApprovalStatus: 0 })">保存</el-button>
      </div>
      <div v-if="approveBut">
        <el-button type="primary" @click="onApprover({ reportApprovalStatus: 3 })">审批</el-button>
        <el-button @click="onApprover({ reportApprovalStatus: 2 })">驳回</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import AccessoryTable from "./accessoryTable.vue";
import { parseStamp } from "@/utils/public.js";
import dutyDaily from "./dutyDaily.vue"; // 日报
import dutyLog from "./dutyLog.vue"; // 日志
import { submitLogOrDailyApi, getDetail, oneClickSync } from "@/api/duty/daily/plan.js";
import { titleConfig, titleConfigApprover, getInfection } from "./confin";
import { flowSubmit } from "@/utils/flow";
export default {
  props: {
    leftTabsKey: {
      type: String,
      default: "值班计划"
    },
    calendarDate: {
      type: Date,
      default: new Date()
    }
  },
  components: {
    AccessoryTable,
    dutyDaily,
    dutyLog
  },
  data() {
    return {
      isEdit: false,
      titleConfig,
      activeNames: ["1", "2", "3"],
      formKey: "dutyLog",
      reportName: "",
      fillIn: {
        creator: "",
        createDeptName: "",
        dutyPersonId: "",
        reportTime: ""
      },
      approverForm: {
        approvalOpinion: ""
      },
      approverRules: {
        approvalOpinion: [{ required: true, message: "请输入", trigger: "blur" }]
      },
      approve: {
        approvalUser: "",
        approvalDept: "",
        approvalTime: ""
      },
      approveBut: false,
      submitBut: false,
      isApprover: false,
      titleBut: false

    };
  },
  computed: {
    roleCode() {
      return JSON.parse(sessionStorage.getItem("role"))?.roleCode;
    }
  },
  watch: {
    "leftTabsKey"(val) {
      if (val == "值班日报") {
        this.formKey = "dutyDaily";
        this.titleConfig[0].title = "值班日报";
      } else {
        this.formKey = "dutyLog";
        this.titleConfig[0].title = "值班日志";
      }
    }
  },
  methods: {
    getParseStamp(date = new Date(), format = "YYYY-MM-DD") {
      return parseStamp(date, format);
    },
    // 提交  保存
    onSubmit(data) {
      this.$refs.dutyForm.$refs.form.validate(async valid => {
        if (valid) {
          const {
            dutyDailyDrillList,
            dutyDailyResourceList,
            dutyDailyInfectionStatusList,
            dutyDailyEpidemicSituationList,
            dutyDailyInboundList,
            dutyDailyWarningResponseList,
            dutyDailyEmergencyResponseList,
            dutyDailyTransformerSubstationRecoverList,
            dutyDailyLineFrankelList,
            dutyDailyOutageList,
            dutyDailyIcingOverallSituationList,
            dutyDailyRouteIcingList,
            dutyDailySurpassTransformerSubstationList,
            dutyDailySurpassLineList,
            dutyDailyLineNumberList
          } = this.$refs.AccessoryTable;
          const params = {
            dutyDailyDrillList,
            dutyDailyResourceList,
            dutyDailyInfectionStatus: getInfection(dutyDailyInfectionStatusList),
            dutyDailyEpidemicSituationList,
            dutyDailyInboundList,
            dutyDailyWarningResponseList,
            dutyDailyEmergencyResponseList,
            dutyDailyTransformerSubstationRecoverList,
            dutyDailyLineFrankelList,
            dutyDailyOutageList,
            dutyDailyIcingOverallSituationList,
            dutyDailyRouteIcingList,
            dutyDailySurpassTransformerSubstationList,
            dutyDailySurpassLineList,
            dutyDailyLineNumberList,
            reportName: this.reportName,
            dutyType: "1",
            dutyDate: parseStamp(this.calendarDate, "YYYY-MM-DD"),
            type: this.formKey == "dutyLog" ? "1" : "2", // 1:日志  2:日报
            ...this.$refs.dutyForm.form,
            ...this.fillIn,
            ...this.approve,
            ...data
          };
          if (data.reportApprovalStatus == 1) {
            this.submitFn(params);
          } else {
            const res = await submitLogOrDailyApi(params);
            if (res) {
              this.$message({ message: `保存成功`, type: "success" });
              this.getDetail();
              this.$emit("leftGetData");
            }
          }
        }
      });
    },
    async submitFn(params) {
      if (!params.id) {
        const res = await submitLogOrDailyApi(params);
        params.id = res;
      }
      const data = {
        bizKey: params.id,
        flowKey: this.formKey == "dutyLog" ? "duty_003" : "duty_004",
        taskId: "task1",
        callbackUrl: this.formKey == "dutyLog" ? "/duty/dutyReport/handleFlowNotice" : "/duty/dutyReport/handleFlow",
        idea: "1",
        variable: params
      };
      const successCallBack = () => {
        this.$message({
          message: `提交成功`,
          type: "success"
        });
        this.getDetail();
        this.$emit("leftGetData");
      };
      await flowSubmit(data, successCallBack, "提交", true);
    },
    // 工作流审批
    gzlAudit(type, variable) {
      const data = {
        bizKey: variable.id,
        flowKey: this.formKey == "dutyLog" ? "duty_003" : "duty_004",
        taskId: "task2",
        callbackUrl: this.formKey == "dutyLog" ? "/duty/dutyReport/handleFlowNotice" : "/duty/dutyReport/handleFlow ",
        idea: type == 2 ? "0" : "1",
        variable,
        ideaMsg: this.approverForm.approvalOpinion
      };
      const successCallBack = () => {
        this.$message({
          message: `${type === 3 ? "审核" : "驳回"}成功`,
          type: "success"
        });
        this.getDetail();
        this.$emit("leftGetData");
      };
      flowSubmit(data, successCallBack, "审核");
    },
    // 审批 // 驳回
    onApprover(data) {
      this.$refs.approverForm.validate(async valid => {
        if (valid) {
          const params = Object.assign({
            approvalOpinion: this.approverForm.approvalOpinion || (data.reportApprovalStatus == 3 ? "同意" : "驳回"),
            id: this.$refs.dutyForm.form.id,
            dutyType: "1",
            type: this.formKey == "dutyLog" ? "1" : "2"
          }, data, this.approve);
          this.gzlAudit(data.reportApprovalStatus, params);
        }
      });
    },
    async getDetail(data) {
      try {
        const time = parseStamp(this.calendarDate, "YYYY-MM-DD");
        const account = JSON.parse(sessionStorage.getItem("account"));
        const type = this.leftTabsKey == "值班日报" ? "2" : "1";
        this.isEdit = false;
        this.approveBut = false;
        this.submitBut = false;
        this.titleBut = false;
        const res = await getDetail(Object.assign({ userId: account.id, reportDate: time, dutyType: "1", type }, data));
        if (res) {
          // 值班审批状态0：编辑中  1：待审批  2：驳回   3：已审批
          // const reportApprovalStatus = res.reportApprovalStatus;
          const arr = Object.keys(this.$refs.dutyForm.form);
          arr.forEach(item => { this.$refs.dutyForm.form[item] = res[item] || ""; });
          this.dataReset(res);
          this.$refs.dutyForm.form.id = res.id;
          this.$refs.dutyForm.form.dutyAttendanceId = res.dutyAttendanceId;
          this.reportName = res.reportName;
          this.fillIn = {
            creator: res.creator,
            dutyPersonId: res.dutyPersonId,
            createDeptName: res.createDeptName,
            reportTime: res.reportTime
          };
          this.approve = {
            approvalUser: res.approvalUser,
            approvalDept: res.approvalDept,
            approvalTime: res.approvalTime
          };
          this.approverForm.approvalOpinion = res.approvalOpinion || "";
          this.titleConfig = res.approvalUserId ? titleConfigApprover : titleConfig;
          if (!res.canFillOut) return;
          if (res.canFillOut.indexOf("operator_staff") != -1) { // 值班员
            this.fillIn = {
              creator: res.creator || account.realName,
              dutyPersonId: res.dutyPersonId || account.id,
              createDeptName: res.createDeptName || sessionStorage.dwbmName,
              reportTime: res.reportTime || parseStamp(new Date())
            };
            this.approveBut = false;
            this.isApprover = false;
            this.operator_staff(res);
          } else if (res.canFillOut.indexOf("operator_leader") != -1) { // 值班长  值班主任
            this.isEdit = false;
            this.submitBut = false;
            this.titleBut = false;
            this.operator_leader(res, account);
          } else if (res.canFillOut.indexOf("shift_leader") != -1) { // 带班领导
            this.shift_leader(res);
            this.isApprover = false;
          }
        }
      } catch (err) {
        this.reportName = "";
        this.$refs.dutyForm.resetForm();
        this.$refs.AccessoryTable.resetData();
      }
    },
    operator_staff(res) {
      if (this.leftTabsKey == "值班日报" || this.leftTabsKey == "值班日志") {
        this.titleConfig = res.reportApprovalStatus == 2 || res.reportApprovalStatus == 3 ? titleConfigApprover : titleConfig;
        if (res.reportApprovalStatus == 1 || res.reportApprovalStatus == 3) {
          this.isEdit = false;
          this.submitBut = false;
          this.titleBut = false;
        } else {
          this.titleBut = this.getParseStamp(this.calendarDate) == this.getParseStamp(new Date());
          this.isEdit = this.getParseStamp(this.calendarDate) == this.getParseStamp(new Date());
          this.submitBut = true;
        }
      } else {
        this.titleConfig = res.approvalUserId ? titleConfigApprover : titleConfig;
        this.isEdit = false;
        this.submitBut = false;
        this.titleBut = false;
      }
    },
    operator_leader(res, account) {
      if (this.leftTabsKey == "值班日报" || this.leftTabsKey == "值班日志") {
        if (res.reportApprovalStatus == 1 && res.isApproved == 1) {
          this.titleConfig = titleConfigApprover;
          this.isApprover = true;
          this.approveBut = true;
          this.approve = {
            approvalUser: account.realName,
            approvalUserId: account.id,
            approvalDept: sessionStorage.dwbmName,
            approvalTime: parseStamp(new Date())
          };
        } else {
          this.titleConfig = res.approvalUserId ? titleConfigApprover : titleConfig;
          this.isApprover = false;
          this.approveBut = false;
        }
      } else {
        this.titleConfig = res.approvalUserId ? titleConfigApprover : titleConfig;
        this.isApprover = false;
        this.approveBut = false;
      }
    },
    shift_leader(res) {
      if (res.reportApprovalStatus == 2 || res.reportApprovalStatus == 3) {
        this.titleConfig = res.approvalUserId ? titleConfigApprover : titleConfig;
      }
    },
    async oneClickSync() {
      const time = parseStamp(this.calendarDate, "YYYY-MM-DD");
      const account = JSON.parse(sessionStorage.getItem("account"));
      const type = this.leftTabsKey == "值班日报" ? "2" : "1";
      const res = await oneClickSync({ userId: account.id, reportDate: time, dutyType: "1", type });
      if (res) {
        const arr = Object.keys(this.$refs.dutyForm.form);
        arr.forEach(item => {
          if (res[item]) this.$refs.dutyForm.form[item] = res[item] || "";
        });
        this.dataReset(res);
      }
    },
    dataReset(res) {
      const Infection = [{ infection: "确诊" }, { infection: "治愈" }, { infection: "疑似" }];
      this.$refs.AccessoryTable.dutyDailyDrillList = this.initializationArr(res.dutyDailyDrillList);
      this.$refs.AccessoryTable.dutyDailyResourceList = this.initializationArr(res.dutyDailyResourceList);
      this.$refs.AccessoryTable.dutyDailyInfectionStatusList = this.initializationArr(res.dutyDailyInfectionStatusList, Infection);
      this.$refs.AccessoryTable.dutyDailyEpidemicSituationList = this.initializationArr(res.dutyDailyEpidemicSituationList);
      this.$refs.AccessoryTable.dutyDailyInboundList = this.initializationArr(res.dutyDailyInboundList);
      this.$refs.AccessoryTable.dutyDailyWarningResponseList = this.initializationArr(res.dutyDailyWarningResponseList);
      this.$refs.AccessoryTable.dutyDailyEmergencyResponseList = this.initializationArr(res.dutyDailyEmergencyResponseList);
      this.$refs.AccessoryTable.dutyDailyTransformerSubstationRecoverList = this.initializationArr(res.dutyDailyTransformerSubstationRecoverList);
      this.$refs.AccessoryTable.dutyDailyLineFrankelList = this.initializationArr(res.dutyDailyLineFrankelList);
      this.$refs.AccessoryTable.dutyDailyOutageList = this.initializationArr(res.dutyDailyOutageList);
      this.$refs.AccessoryTable.dutyDailyIcingOverallSituationList = this.initializationArr(res.dutyDailyIcingOverallSituationList);
      this.$refs.AccessoryTable.dutyDailyRouteIcingList = this.initializationArr(res.dutyDailyRouteIcingList);
      this.$refs.AccessoryTable.dutyDailySurpassTransformerSubstationList = this.initializationArr(res.dutyDailySurpassTransformerSubstationList);
      this.$refs.AccessoryTable.dutyDailySurpassLineList = this.initializationArr(res.dutyDailySurpassLineList);
      this.$refs.AccessoryTable.dutyDailyLineNumberList = this.initializationArr(res.dutyDailyLineNumberList);
    },
    initializationArr(data, falg) {
      const arr = falg || [{}];
      if (data && data.length != 0) {
        return data;
      } else {
        return arr;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.wrapper {
  padding: 20px 40px;
  background-color: #fff;
  border-radius: 4px;
  height: 100%;
  overflow-y: auto;
  font-size: 16px;
  box-sizing: border-box;
}

.title-but {
  display: flex;
  justify-content: flex-end;
}

.approverForm {
  :deep(.el-form-item__label) {
    font-size: 18px;
  }
}

.footer-btn {
  >div {
    display: flex;
    align-content: center;
    justify-content: center;
  }
}
</style>
